import React, { useEffect, useState } from "react";
import '../proof.css';
import '../../Login/login.css';
import '../../../App.css'
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading, Toast } from "antd-mobile";
import { useDispatch } from "react-redux";
import { isProofContact, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "@/store/actions/userState";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import icon_logo_aliexpress from '@/assets/icon_logo_aliexpress.png'
import icon_logo_bolt_food from '@/assets/icon_logo_bolt_food.png'
import icon_logo_cryptomania from '@/assets/icon_logo_cryptomania.png'
import icon_logo_facebook from '@/assets/icon_logo_facebook.png'
import icon_logo_google_chat from '@/assets/icon_logo_google_chat.png'
import icon_logo_google_meet from '@/assets/icon_logo_google_meet.png'
import icon_logo_instagram from '@/assets/icon_logo_instagram.png'
import icon_logo_jiji_nigeria from '@/assets/icon_logo_jiji_nigeria.png'
import icon_logo_jumia_food from '@/assets/icon_logo_jumia_food.png'
import icon_logo_jumia_shopping from '@/assets/icon_logo_jumia_shopping.png'
import icon_logo_linkedin from '@/assets/icon_logo_linkedin.png'
import icon_logo_telegramx from '@/assets/icon_logo_telegramx.png'
import icon_logo_tiktok from '@/assets/icon_logo_tiktok.png'
import icon_logo_translate_all_languages from '@/assets/icon_logo_translate_all_languages.png'
import icon_logo_x from '@/assets/icon_logo_x.png'
import icon_app_selected from '@/assets/icon_app_selected.png'
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import { isEmptyString, toTrimString } from "@/utils/utils";
import AddHomeEvent from "@/utils/addHomeEvent";
import PrivacyPolicyLink from "@/components/PrivacyPolicyLink/PrivacyPolicyLink";
import { reqSaveEvent, reqSaveFrequentlyApps, reqUserState } from "@/store/actions/apiServices";




export default function ProofFrequentlyApps() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的用户状态信息
    const [userStateInfo, setUserStateInfo] = useState({});

    //常用app列表状态
    const [appList, setAppList] = useState([])

    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);
        if (success && resObj) {
            console.log("Launch-signOrderId: " + resObj.signOrderId);
            setUserStateInfo(resObj);

            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId);
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus);
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus);
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus);
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus);
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay));
            console.log("Launch-isHomeReviewing: " + isHomeReviewing);
            console.log("Launch-isHomeReject: " + isHomeReject);
            console.log("Launch-isHomeLoaning: " + isHomeLoaning);
            console.log("Launch-isHomeRepay: " + isHomeRepay);
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan);
            console.log("Launch-isHomeSigning: " + isHomeSigning);

            //跳转状态页
            if (isHomeSigning) {
                history.replace('/guide');
                return;

            } else if (isHomeReviewing) {
                history.replace('/review');
                return;

            } else if (isHomeReject) {
                history.replace('/reject');
                return;

            } else if (isHomeLoaning) {
                history.replace('/loaning');
                return;

            } else if (isHomeRepay) {
                history.replace('/repay');
                return;
            }

            //判断下是否已经做完所有认证
            if (resObj.isProofFinish === true) {
                //跳转申请页
                history.replace('/apply');
                return;
            }

            //是否为号码认证
            if (isProofMobile(resObj.stepTitle)) {
                //跳转申请页
                history.replace('/proofmobile');
                return;
            }

            //是否为常用app认证
            if (isProofFrequentlyUsedApps(resObj.stepTitle)) {
                //跳转申请页

                return;
            }

            //是否为人脸认证
            if (isProofFace(resObj.stepTitle)) {
                history.replace('/proofface');
                return;
            }

            if (isProofContact(resObj.stepTitle)) {
                if (window.isSupportContactPicker === true) {
                    history.replace('/proofcontact');
                } else {
                    history.replace('/proofcontactinput');
                }
                return;
            }

            history.replace('/proof');
        }
    };

    const checkUserStateInfo = async () => {
        try {
            setMaskVisible(true);
            reqUserState(PageTag.PROOF_FREQUENTLY_APPS, onReqUserStateCallback);

        } catch (e) {
            console.log(e)
        }
    }

    //请求保存接口
    const doSaveApps = async () => {
        try {
            setMaskVisible(true)

            let appListContent = ""
            appList.forEach(item => {
                if (item.selected) {
                    if (appListContent.length > 0) {
                        appListContent = appListContent + "," + item.label
                    } else {
                        appListContent = item.label
                    }
                }
            })
            appListContent = toTrimString(appListContent + "")

            //保存打点
            reqSaveEvent("PROOF_FREQUENTLY_APPS_COMMIT_CLICK", appListContent)

            //拦截
            if (isEmptyString(appListContent)) {
                setMaskVisible(false)
                Toast.show("Please select at least one app")
            } else {
                reqSaveFrequentlyApps(appListContent, (success, resObj) => {
                    setMaskVisible(false)
                    if (success) {
                        checkUserStateInfo();
                    }
                });
            }
        } catch (e) {
            console.log(e)
        }
    }

    const onHandleAppClick = (index, selected) => {
        if (appList.length > index) {
            const list = [...appList]
            const item = list[index]
            item.selected = !selected

            setAppList(list)

            if (!selected) {
                reqSaveEvent("PROOF_FREQUENTLY_APPS_CLICK", item.label)
            }
        }
    }

    const onHandleSubmit = async () => {
        try {
            doSaveApps();

        } catch (e) {
            console.log(e)
        }
    }

    //点击返回
    const onHandleNavGoBack = () => {
        history.replace('/home');
    }

    //初始化app列表
    const initAppList = () => {
        const list = [
            { label: "TikTok", icon: icon_logo_tiktok, selected: false },
            { label: "Jumia Food", icon: icon_logo_jumia_food, selected: false },
            { label: "Google Chat", icon: icon_logo_google_chat, selected: false },
            { label: "JUMIA Online Shopping", icon: icon_logo_jumia_shopping, selected: false },
            { label: "X", icon: icon_logo_x, selected: false },
            { label: "Cryptomania", icon: icon_logo_cryptomania, selected: false },
            { label: "Jiji Nigeria", icon: icon_logo_jiji_nigeria, selected: false },
            { label: "Instagram", icon: icon_logo_instagram, selected: false },
            { label: "LinkedIn", icon: icon_logo_linkedin, selected: false },
            { label: "Bolt Food", icon: icon_logo_bolt_food, selected: false },
            { label: "AliExpress", icon: icon_logo_aliexpress, selected: false },
            { label: "Facebook", icon: icon_logo_facebook, selected: false },
            { label: "Telegram X", icon: icon_logo_telegramx, selected: false },
            { label: "Google Meet", icon: icon_logo_google_meet, selected: false },
            { label: "Translate All Languages", icon: icon_logo_translate_all_languages, selected: false }
        ]
        setAppList(list)
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        setAddHomeMaskVisible(false)
    }

    useEffect(() => {
        initAppList();

        checkUserStateInfo();

        reqSaveEvent("PROOF_FREQUENTLY_APPS_START");

        return () => {
            reqSaveEvent("PROOF_FREQUENTLY_APPS_END");
        }
    }, [])

    return (
        <div className="proofRoot">
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{userStateInfo.pageTitle}</ProofNavigateBar>

            <div className="proofContent ">
                <div className="proofAppList proofTopMargin16Px">
                    {appList.map((value, index) => {
                        if (value.selected) {
                            return (
                                <div className="proofAppContent proofAppContentSelected" key={index} onClick={() => { onHandleAppClick(index, true) }}>
                                    <div className="proofAppIconSelectedContent">
                                        <img className="proofAppIconSelected" src={icon_app_selected} alt="" />
                                    </div>
                                    <img className="proofAppIcon" src={value.icon} alt="" />
                                    <span className="proofAppName">{value.label}</span>
                                </div>
                            )
                        } else {
                            return (
                                <div className="proofAppContent" key={index} onClick={() => { onHandleAppClick(index, false) }}>
                                    <div className="proofAppIconSelectedContent">
                                        <div className="proofAppIconUnSelect" ></div>
                                    </div>
                                    <img className="proofAppIcon" src={value.icon} alt="" />
                                    <span className="proofAppName">{value.label}</span>
                                </div>
                            )
                        }
                    })}

                </div>
            </div>

            <div className="proofApplyBtn" onClick={onHandleSubmit}>
                <div className="mainButtonGradient">Next</div>
            </div>

            <PrivacyPolicyLink pageTag={userStateInfo.pageTitle} showCheckbox={false} linkText="Privacy policy" />

            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}